import { Button, ColumnProps, Modal, Select, Space, Table, Trigger, TriggerInstance } from '@kedacom/react-next'
import React, { useEffect, useRef, useState } from 'react'
import shallow from 'zustand/shallow'
import { useBasicInfoStore } from '../store'
import { DeleteIcon, StyledWrap } from './style'
import { fetchLoadMeetingRoomByRegion, fetchLoadRegions } from '@/api/create'
import { ICriteria, IRoomData, ISelectItem, numData } from '../interface'
import { getDefaultMeetingCriteria } from '../translator'
import MorePopUpPanel from './MorePopUpPanel'
import Alert, { Confirm, confirmModal } from '@/components/Alert'
import { store as addMtSelectedStore } from '@/components/AddMt/blocks/selected/store'
import { transRoomData } from '../translator'
import { v4 as uuidv4 } from 'uuid'
import { useUserAllStore } from '../../user/all/store'
import { useMeetingParamsStore } from '../../meetingParams/store'
import { checkScale } from '../../../store.combine'
import { t } from 'i18next'
import { clearCheckedMeetingRooms, loadMeetingRooms } from '../store.room'
import { addRooms } from '../../user/store.combine'

interface ITableData {
	id: string
	day: string
	region_name: string
	name: React.ReactNode
}
const columns: ColumnProps<ITableData>[] = [
	{
		title: t('日期'),
		dataKey: 'day',
	},
	{
		title: t('区域'),
		dataKey: 'region_name',
	},
	{
		title: t('会议室'),
		dataKey: 'name',
	},
]

export default function SearchRoomModal() {
	const { _isSearchRoomDialogShow, meetingCriteriaList, roomData, repeat, update } = useBasicInfoStore(
		(state) => ({
			_isSearchRoomDialogShow: state._isSearchRoomDialogShow,
			meetingCriteriaList: state.meetingCriteriaList,
			roomData: state.roomData,
			repeat: state.repeat,
			update: state.update,
		}),
		shallow
	)
	const [regionList, setRegionList] = useState<ISelectItem[]>([{ label: t('请选择区域'), value: 0 }])
	const [criteriaList, setCriteriaList] = useState(getDefaultMeetingCriteria())
	const [roomList, setRoomList] = useState<IRoomData | null>(null)
	const searchModelRef = useRef<TriggerInstance>(null)

	useEffect(() => {
		if (_isSearchRoomDialogShow) {
			//加载区域列表
			fetchLoadRegions()
				.then((data) => {
					let arr = data.map((item) => ({ label: item.area, value: Number(item.id) }))
					setRegionList([{ label: t('请选择区域'), value: 0 }, ...arr])
				})
				.catch(() => {
					setRegionList([{ label: t('请选择区域'), value: 0 }])
				})

			//设置搜索规则
			if (meetingCriteriaList.length !== 0) {
				setMeetingCriteriaList()
			} else {
				setCriteriaList(getDefaultMeetingCriteria())
			}

			//设置推荐列表
			setRoomList(roomData)
		}
	}, [_isSearchRoomDialogShow])

	const setMeetingCriteriaList = async () => {
		let arr: ICriteria[] = []
		for (let item of meetingCriteriaList) {
			let _meetingRoomsList: ISelectItem[] = [{ label: t('请选择会议室'), value: '0' }]
			if (item.region_id !== 0) {
				let data = await fetchLoadMeetingRoomByRegion(item.region_id)
				_meetingRoomsList.push(...data.map((item) => ({ label: item.name, value: item.id.toString() })))
			}
			arr.push({
				regionName: item.region_name,
				deviceIds: item.device_ids,
				num: item.num,
				regionId: item.region_id,
				upSeating: item.up_seating,
				downSeating: item.down_seating,
				meetingRoomId: '0',
				meetingRoomsList: _meetingRoomsList,
			})
		}
		setCriteriaList(arr)
	}

	const addArea = () => {
		setCriteriaList((preVal) => [...preVal, ...getDefaultMeetingCriteria()])
	}

	const deleteArea = (index: number) => {
		let arr = [...criteriaList]
		arr.splice(index, 1)
		setCriteriaList(arr)
	}

	const handleSearch = () => {
		let flag = true
		for (let i = 0; i < criteriaList.length; i++) {
			let criteria = criteriaList[i]
			if (criteria.regionId === 0) {
				Alert(t('请选择区域'))
				flag = false
				break
			}
			if (criteria.num === 0) {
				Alert(t('请选择数量'))
				flag = false
				break
			}
		}
		if (!flag) return
		if (criteriaList.length > 10) {
			Alert(t('最多可添加10个会议室'))
			return
		}
		clearCheckedMeetingRooms(
			() => {
				loadMeetingRooms(criteriaList, (data) => {
					setRoomList(transRoomData(data))
				})
			},
			() => {},
			<div>
				{t('该操作会释放您锁定和预定的所有会议室，是否继续?')}
				<br />
				<span style={{ color: '#AAA', fontSize: '14px', lineHeight: '23px' }}>
					{t('被释放的会议室在【发言方】,【轮询】,【画面合成】中的设置，将无效')}
				</span>
			</div>,
			true
		)
	}
	const handleOk = () => {
		if (!roomList) {
			Confirm(t('您尚未推荐任何会议室,确定退出？'), function () {
				update({ _isSearchRoomDialogShow: false })
			})
			return
		}
		let isChange = false //判断是否修改条件
		if (criteriaList.length !== meetingCriteriaList.length) {
			isChange = true
		} else {
			for (let i = 0; i < criteriaList.length; i++) {
				if (
					criteriaList[i].deviceIds !== meetingCriteriaList[i].device_ids ||
					criteriaList[i].num !== meetingCriteriaList[i].num ||
					criteriaList[i].regionId !== meetingCriteriaList[i].region_id ||
					criteriaList[i].upSeating !== meetingCriteriaList[i].up_seating ||
					criteriaList[i].downSeating !== meetingCriteriaList[i].down_seating
				) {
					isChange = true
					break
				}
			}
		}
		if (isChange) {
			confirmModal({
				msg: <div>{t('会议室查找条件已修改，是否重新推荐？')}</div>,
				okText: t('重新推荐'),
				cancelText: t('放弃修改'),
				onOk: () => {
					handleSearch()
				},
				onCancel: () => {
					setRoomData()
				},
			})
		} else {
			setRoomData()
		}
	}

	//设置会议室信息
	const setRoomData = () => {
		let usefulRooms = roomList?.data[0].meeting_rooms.filter((item) => item.name) ?? []
		const tree = useUserAllStore.getState().tree
		let num = tree.length //当前与会方人数
		for (let i = 0; i < tree.length; i++) {
			let hasIn = false
			if (tree[i].mcc.account_type === 2) {
				for (let r = 0; r < usefulRooms.length; r++) {
					//数字和字符串比较  在与会方列表的会议室有e164号
					if (usefulRooms[r].e164 === tree[i].mcc.account) {
						hasIn = true
					}
				}
				if (!hasIn) {
					//不存在 长度增加1
					num++
				}
			}
		}
		const callBack = () => {
			if (!repeat) {
				addRooms(
					usefulRooms.map((x) => ({
						account: x.e164,
						account_type: 2,
						name: x.name,
						protocol: 255,
						bitrate: useMeetingParamsStore.getState().rate,
						e164: x.e164,
					}))
				)
				addMtSelectedStore.getState().delSelectedRooms(
					usefulRooms.map((x) => ({
						account: x.e164,
						accountType: 2,
						name: x.name,
						protocol: 255,
						bitrate: useMeetingParamsStore.getState().rate,
						bitrateType: 0,
						e164: x.e164,
					}))
				)
			}
			update({ _isSearchRoomDialogShow: false })
			update({ roomData: roomList ? { ...roomList } : null })
		}

		let type = checkScale(num) //判断规模
		if (type === 1) {
			callBack()
		} else {
			confirmModal({
				msg: (
					<div>
						{type === 2
							? t('添加的与会方数已超过当前会议规模,部分终端可能无法正常入会')
							: t('添加的与会方数已超过当前会议接入数上限，部分终端可能无法正常入会')}
					</div>
				),
				okText: t('继续邀请'),
				cancelText: t('返回修改'),
				onOk: () => {
					callBack()
				},
			})
		}
	}

	const handleCancel = () => {
		if (roomList && roomList.status !== 3) {
			clearCheckedMeetingRooms(
				() => {
					update({ _isSearchRoomDialogShow: false, meetingCriteriaList: [] })
					addMtSelectedStore.getState().delAllSelectedRooms()
				},
				() => {},
				<div>
					{t('该操作会释放您锁定和预定的所有会议室，是否继续?')}
					<br />
					<span style={{ color: '#AAA', fontSize: '14px', lineHeight: '23px' }}>
						{t('被释放的会议室在【发言方】,【轮询】,【画面合成】中的设置，将无效')}
					</span>
				</div>,
				true
			)
		} else {
			update({ _isSearchRoomDialogShow: false, meetingCriteriaList: [] })
		}
	}

	const getTableData = () => {
		if (!roomList) return []
		let arr: ITableData[] = []
		for (let i = 0; i < roomList.data.length; i++) {
			let item = roomList.data[i]
			for (let j = 0; j < item.meeting_rooms.length; j++) {
				arr.push({
					id: uuidv4(),
					day: j === 0 ? item.day : '',
					region_name: item.meeting_rooms[j].region_name,
					name: item.meeting_rooms[j].name || <span style={{ color: 'red' }}>{t('无')}</span>,
				})
			}
		}
		return arr
	}

	return (
		<Modal
			className="search-room-modal"
			title={t('查找会议室')}
			height={545}
			width={700}
			open={_isSearchRoomDialogShow}
			needFooter={false}
			onCancel={() => {
				update({ _isSearchRoomDialogShow: false })
			}}
		>
			<StyledWrap>
				<div className="top-title">
					<span>{t('请选择所需的会议室：')}</span>
					<span className="add-area" onClick={addArea}>
						{t('增加区域')}
					</span>
				</div>
				<div className="criterion-wrap">
					{criteriaList.map((criteria, index) => (
						<div className="area-wrap" key={index}>
							<Select
								className="area-select"
								placeholder={t('请选择区域')}
								options={regionList}
								value={criteria.regionId}
								onChange={async (e, v, obj) => {
									let _meetingRoomsList: ISelectItem[] = [{ label: t('请选择会议室'), value: '0' }]
									let arr = [...criteriaList]
									if (v === 0) {
										arr[index].num = 0
									} else {
										let data = await fetchLoadMeetingRoomByRegion(v)
										_meetingRoomsList.push(
											...data
												.filter((item) => !!item.video)
												.map((item) => ({ label: item.name, value: item.id }))
										)
										arr[index].num = 1
									}
									arr[index].regionId = v
									arr[index].regionName = obj.label
									arr[index].meetingRoomsList = _meetingRoomsList
									arr[index].meetingRoomId = '0'
									setCriteriaList(arr)
								}}
							/>
							<Select
								className="area-select"
								placeholder={t('请选择数量')}
								options={numData}
								value={criteria.num}
								onChange={(e, v) => {
									let arr = [...criteriaList]
									arr[index].num = v
									if (v > 1) {
										arr[index].meetingRoomId = '0'
									}
									setCriteriaList(arr)
								}}
							/>
							<Select
								className="area-select"
								placeholder={t('请选择会议室')}
								disabled={criteria.num > 1}
								options={criteria.meetingRoomsList}
								value={criteria.meetingRoomId}
								onChange={(e, v) => {
									let arr = [...criteriaList]
									arr[index].meetingRoomId = v
									arr[index].num = 1
									setCriteriaList(arr)
								}}
							/>
							<Trigger
								ref={searchModelRef}
								popup={
									<MorePopUpPanel
										data={criteria}
										onOk={({ devicesIds, personNumLowerLimit, personNumUpperLimit }) => {
											searchModelRef.current?.close()
											let arr = [...criteriaList]
											arr[index].upSeating = personNumUpperLimit
											arr[index].downSeating = personNumLowerLimit
											arr[index].deviceIds = devicesIds
											setCriteriaList(arr)
										}}
										onCancel={() => {
											searchModelRef.current?.close()
										}}
									/>
								}
								popupPlacement="bottomStart"
							>
								<span className="more">{t('更多选项')}</span>
							</Trigger>

							{criteriaList.length > 1 && (
								<DeleteIcon className="delete" onClick={() => deleteArea(index)} />
							)}
						</div>
					))}
				</div>
				<div className="middle-title">
					<span>{t('已为您推荐的会议室：')}</span>
					<Button onClick={handleSearch}>{t('推荐')}</Button>
				</div>
				{roomList && (
					<div className="recommend-result">
						<Table
							key="id"
							fixHeader
							showOrderColumn={false}
							showSelectColumn={false}
							height={200}
							columns={columns}
							data={getTableData()}
							i18n={{ order: t('序号') }}
							nodata={t('暂无数据')}
						></Table>
					</div>
				)}
				<Space className="btns">
					<Button onClick={handleOk}>{t('确认')}</Button>
					<Button onClick={handleCancel}>{t('取消')}</Button>
				</Space>
			</StyledWrap>
		</Modal>
	)
}
